<template>
  <van-nav-bar title="登录"></van-nav-bar>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="UserForm.username" name="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }, {
        pattern: /^\w{6,16}$/, message: '用户名格式不正确'
      }]" />
      <van-field v-model="UserForm.password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }, {
                pattern: /^\w{6,16}$/, message: '用户名格式不正确'
      }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
    <van-row justify="end">
      <router-link class="link" to="/register">注册账号</router-link>
    </van-row>

  </van-form>

</template>
<script lang="ts" setup>
import type { LoginUser } from '@/types/data'
import useTokenStore from '@/stores/token'
import { login } from '@/api/user'
import { reactive } from 'vue'
import type { AxiosError } from 'axios'
import { Notify } from 'vant'
import { useRouter } from 'vue-router'
import 'vant/es/notify/style';
const { updateToken } = useTokenStore()
const router = useRouter()
const UserForm = reactive<LoginUser>({
  username: '',
  password: ''
})
const onSubmit = async (values: LoginUser) => {
  try {
    const result = await login(values)
    updateToken(result.data.token) // 设置token
    Notify({ type: "success", message: "登录成功" })
    router.push("/") // 跳转到主页
  } catch (error) {
    const e = error as AxiosError
    Notify({ type: "danger", message: e.message })
  }
}
</script>
<style scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
}
</style>